/*
 * Copyright 2016 jeasonlzy(廖子尧)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.delivery.callback;

import android.content.Context;
import android.text.TextUtils;

import com.android.delivery.App;
import com.android.delivery.entity.LoginInfo;
import com.android.delivery.util.ToastUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.net.ConnectException;
import java.net.UnknownHostException;

/**
 * ================================================
 * 作    者：jeasonlzy（廖子尧）Github地址：https://github.com/jeasonlzy
 * 版    本：1.0
 * 创建日期：2016/1/14
 * 描    述：对于网络请求是否需要弹出进度对话框
 * 修订历史：
 * ================================================
 */
public abstract class DialogCallback<T> extends JsonCallback<T> {

//    private Dialog dialog;

    static String AUTHORIZATION = "Authorization";
    static String BEARER = "Bearer ";
    private LoadingPopupView loadingPopup;

    private void initDialog(Context activity) {
//        if (dialog == null){
//            dialog = new Dialog(activity);
//            dialog.setCanceledOnTouchOutside(false);
////            dialog.setContentView(R.layout.dialog_loading);
////            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
//            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
//                @Override
//                public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
//                    if(i==KeyEvent.KEYCODE_BACK){
//                    }
//                    return false;
//                }
//            });
//        }

        if (loadingPopup == null) {
            loadingPopup = (LoadingPopupView) new XPopup.Builder(activity)
                    .asLoading("正在加载中")
                    .show();
        }


//        loadingPopup.postDelayed(new Runnable() {
//            @Override
//            public void run() { loadingPopup.setTitle("正在加载中啊啊啊"); }
//        },1000);
//        loadingPopup.delayDismissWith(3000,new Runnable() {
//            @Override
//            public void run() {
//                toast("我消失了！！！");
//            }
//        });

    }

    public DialogCallback(Context activity) {
        super();
        if (ObjectUtils.isNotEmpty(activity)) {
            initDialog(activity);

        }

    }

    public DialogCallback() {
        super();

    }

    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);
        if (loadingPopup != null && !loadingPopup.isShow()) {
            loadingPopup.show();
        }
        LoginInfo loginInfo = App.Companion.getInstance().getLoginInfo();
        if (loginInfo != null) {
            request.headers(AUTHORIZATION, BEARER + loginInfo.getToken()); //header不支持中文，不允许有特殊字符
        }
    }

    @Override
    public void onFinish() {
        super.onFinish();
        //网络请求结束后关闭对话框
        if (loadingPopup != null && loadingPopup.isShow()) {
            loadingPopup.dismiss();
        }
    }

    @Override
    public void onError(Response<T> response) {
        super.onError(response);
        if (response.getException() instanceof ConnectException || response.getException() instanceof UnknownHostException) {
            ToastUtils.showShort(App.Companion.getInstance().getApplicationContext(), "网络连接不可用，请稍后重试");
        } else if (response != null && !TextUtils.isEmpty(response.getException().getMessage())) {
            ToastUtils.showShort(App.Companion.getInstance().getApplicationContext(), response.getException().getMessage());
        }
    }
}
